import React from 'react';
import _ from 'lodash';
import styled from 'styled-components';
import { utils, NumberView } from '@/components/BaseTable';
import { Icon, Tooltip } from 'antd';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import { Link } from 'umi';
import YearsRender from '../components/YearsRender';

dayjs.extend(utc);
dayjs.extend(isSameOrBefore);

const TableCell = styled.div`
  display: flex;
  align-items: center;
  text-align: center;
  justify-content: center;
  flex-direction: column;
`;
// 签约与回款
const signAndReturn = [
  'totalValue', // 总货值
  'accumulativeSold', // 累计已售
  'accumulativeReturn', // 累计已回款
  'signNotReturn', // 已签未回
  'notSignNotReturn', // 未签未回
  'signReturnRate', // 累计签约回款率
];
// 年度数据
const yearData = [
  'yearEarlyReceivable', // 年初应收账款
  'yearSign', // 年度签约
  'annualActualIncrementalReturn', // 年度实际数-增量回款
  'annualActualStoreReturn', // 年度实际数-存量回款
  'annualCalculateIncrementalReturn', // 年度测算数-增量回款
  'annualCalculateStoreReturn', // 年度测算数-存量回款
  'annualAdjustIncrementalReturn', // 年度调整数-增量回款
  'annualAdjustStoreReturn', // 年度调整数-存量回款
  'yearSignNotReturn', // 年度已签未回回款数
  'yearEarlyRefund', // 年初应退
  'annualTotalIncrementalReturn', // 年度回款合计-增量回款
  'annualTotalStoreReturn', // 年度回款合计-存量回款
  'annualTotalReturnTotal', // 年度回款合计-回款合计
  'annualTotalYearEndReceivable', // 年度回款合计-年末应收账款
];
// 实际月
const actualMonth = [
  'monthEarlyReceivable', // 月初应收账款
  'monthSign', // 月度签约
  'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
  'monthlyTotalStoreReturn', // 月度回款合计-存量回款
  'monthlyTotalReturnTotal', // 月度回款合计-回款合计
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];
// 当前月
const currentMonth = [
  'monthEarlyReceivable', // 月初应收账款
  'monthSign', // 月度签约
  'monthlyActualIncrementalReturn', // 月度实际数-增量回款
  'monthlyActualStoreReturn', // 月度实际数-存量回款
  'monthlyCalculateIncrementalReturn', // 月度测算数-增量回款
  'monthlyCalculateStoreReturn', // 月度测算数-存量回款
  'monthlyAdjustIncrementalReturn', // 月度调整数-增量回款
  'monthlyAdjustStoreReturn', // 月度调整数-存量回款
  'monthSignNotReturn', // 月度已签未回回款数
  'refundable', // 期初应退回款数
  'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
  'monthlyTotalStoreReturn', // 月度回款合计-存量回款
  'monthlyTotalReturnTotal', // 月度回款合计-回款合计
  'monthlyTotalMonthEndReceivable', // 月度回款合计-月末应收账款
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];
// 计划月
const planMonth = [
  'monthEarlyReceivable', // 月初应收账款
  'monthSign', // 月度签约
  'monthlyCalculateIncrementalReturn', // 月度测算数-增量回款
  'monthlyCalculateStoreReturn', // 月度测算数-存量回款
  'monthlyAdjustIncrementalReturn', // 月度调整数-增量回款
  'monthlyAdjustStoreReturn', // 月度调整数-存量回款
  'monthSignNotReturn', // 月度已签未回回款数
  'monthlyTotalIncrementalReturn', // 月度回款合计-增量回款
  'monthlyTotalStoreReturn', // 月度回款合计-存量回款
  'monthlyTotalReturnTotal', // 月度回款合计-回款合计
  'monthlyTotalMonthEndReceivable', // 月度回款合计-月末应收账款
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    if (value.pid === pid) {
      if (hasChildren(list, value)) {
        value.children = [];
        value.children = buildTree(list, value.id);
      }
      tree.push(value);
    }
  });
  return tree;
};

export const getFixedColumns = (currentYear, currentMonths, match, currentVersion) => {
  const { level1, level2, project, stage, version, category } = match.params;
  // 获取版本归属月份---begin
  let getVersionAffiliationMonth = dayjs().format('YYYY-MM');
  // 如果是预算版本类型 取 来源版本的归属月份
  if (currentVersion?.versionType === 'budget') {
    getVersionAffiliationMonth = dayjs(currentVersion?.sourceAffiliationMonth).format('YYYY-MM');
  } else {
    getVersionAffiliationMonth = dayjs(currentVersion?.affiliationMonth).format('YYYY-MM');
  }
  // 获取版本归属月份---end
  let fixedColumns = [
    {
      key: 'name',
      dataKey: 'name',
      title: '',
      width: 300,
      frozen: 'left',
      headerRenderer: () => <div>分期/组团/业态/楼栋</div>,
      dataGetter: ({ rowData }) => {
        const text = rowData.name;
        const result = {
          text,
        };
        result.textFirst = false;
        if (rowData.isSupply === 0) {
          result.tags = [{ text: 'check', color: 'orange' }];
        }
        return result;
      },
      cellRenderer: data => {
        let isEdit = false;
        const title = data.rowData.name;
        // 是否是编制状态
        if (!_.isEmpty(currentVersion)) {
          if (
            // _.includes(this.props.Permissions.buttons, 'button_1040204') &&
            currentVersion.versionStateCode === 'not_prepared' ||
            currentVersion.versionStateCode === 'organization' ||
            currentVersion.versionStateCode === 'examined_approved' ||
            currentVersion.versionStateCode === 'failure_approved'
          ) {
            isEdit = true;
          }
        }
        if (data.rowData.type === 'org_group' && isEdit) {
          const url = `/OperatingPlan/ReturnMoneyPlan/${level1}/${level2}/${project}/${stage}/${category}/${version}/${data.rowData.id}/edit`;
          return (
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div className="ellipsis">
                <Tooltip placement="topLeft" title={title}>
                  <Link to={url}>{title}</Link>
                </Tooltip>
              </div>
              &nbsp;
              {data.rowData.isEstablishment === 1 && (
                <Icon
                  type="check-circle"
                  twoToneColor="#52c41a"
                  theme="twoTone"
                  style={{ marginTop: 2 }}
                />
              )}
            </div>
          );
        }
        return (
          <div className="ellipsis">
            <Tooltip placement="topLeft" title={title}>
              {title}
            </Tooltip>
          </div>
        );
      },
    },
    {
      key: 'carryOverTimeStr',
      dataKey: 'carryOverTimeStr',
      align: 'center',
      width: 100,
    },
  ];
  _.forEach(signAndReturn, v => {
    const isPercentage = v === 'signReturnRate';
    fixedColumns.push({
      key: v,
      dataKey: v,
      title: isPercentage ? '（%）' : '金额（万元）',
      align: 'right',
      width: 100,
      dataGetter: ({ rowData }) => {
        let val = '';
        if (isPercentage) {
          val = `${(rowData.signAndReturn[v] * 100).toFixed(3)}%`;
        } else {
          val = rowData.signAndReturn[v] / 10000;
        }
        return val;
      },
      cellRenderer: data => {
        let val = '';
        if (isPercentage) {
          val = data.cellData;
        } else {
          val = <NumberView {...data} precision={4} />;
        }
        return val;
      },
    });
  });
  // 筛选项里是否有年度合计
  if (_.includes(currentMonths, '14'.toString())) {
    const newYearDataArr = [];
    _.forEach(yearData, v => {
      newYearDataArr.push({
        key: `${currentYear}-${v}`,
        dataKey: `${currentYear}-${v}`,
        title: '金额（万元）',
        align: 'right',
        width: 100,
        dataGetter: ({ rowData }) => [rowData.yearData ? rowData.yearData[v] / 10000 : 0],
        cellRenderer: <NumberView precision={4} />,
      });
    });
    fixedColumns = _.concat(fixedColumns, newYearDataArr);
  }
  // 月份
  for (let i = 1; i <= 12; i += 1) {
    if (_.includes(currentMonths, i.toString())) {
      // 是否是当前时间之前
      const isCurrentTimeBefore = dayjs(`${currentYear}-${i}`).isBefore(getVersionAffiliationMonth);
      // 是否是当前时间
      const isCurrentTime = dayjs(`${currentYear}-${i}`).isSame(getVersionAffiliationMonth);
      // 实际月
      if (!isCurrentTime && isCurrentTimeBefore) {
        _.forEach(actualMonth, v => {
          // 是百分比
          const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
          fixedColumns.push({
            key: `${currentYear}-${i}-${v}`,
            dataKey: `${currentYear}-${i}-${v}`,
            title: isPercentage ? '（%）' : '金额（万元）',
            align: 'right',
            width: 100,
            dataGetter: ({ rowData }) => {
              let val = 0;
              if (isPercentage) {
                val = rowData.monthDataList[i - 1]
                  ? `${(rowData.monthDataList[i - 1][v] * 100).toFixed(3)}%`
                  : '0.0%';
              } else {
                val = rowData.monthDataList[i - 1] ? rowData.monthDataList[i - 1][v] / 10000 : 0.0;
              }
              return val;
            },
            cellRenderer: data => {
              let val = '';
              if (isPercentage) {
                val = data.cellData;
              } else {
                val = <NumberView {...data} precision={4} />;
              }
              return val;
            },
          });
        });
      }
      // 当前月
      if (isCurrentTime) {
        _.forEach(currentMonth, v => {
          // 是百分比
          const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
          fixedColumns.push({
            key: `${currentYear}-${i}-${v}`,
            dataKey: `${currentYear}-${i}-${v}`,
            title: isPercentage ? '（%）' : '金额（万元）',
            align: 'right',
            width: 100,
            dataGetter: ({ rowData }) => {
              let val = 0;
              if (isPercentage) {
                val = rowData.monthDataList[i - 1]
                  ? `${(rowData.monthDataList[i - 1][v] * 100).toFixed(3)}%`
                  : '0.0%';
              } else {
                val = rowData.monthDataList[i - 1] ? rowData.monthDataList[i - 1][v] / 10000 : 0.0;
              }
              return val;
            },
            cellRenderer: data => {
              let val = '';
              if (isPercentage) {
                val = data.cellData;
              } else {
                val = <NumberView {...data} precision={4} />;
              }
              return val;
            },
          });
        });
      }
      // 计划月
      if (!isCurrentTime && !isCurrentTimeBefore) {
        _.forEach(planMonth, v => {
          // 是百分比
          const isPercentage = v === 'signReturnRate' || v === 'annualOverallReturnRate';
          fixedColumns.push({
            key: `${currentYear}-${i}-${v}`,
            dataKey: `${currentYear}-${i}-${v}`,
            title: isPercentage ? '（%）' : '金额（万元）',
            align: 'right',
            width: 100,
            dataGetter: ({ rowData }) => {
              let val = 0;
              if (isPercentage) {
                val = rowData.monthDataList[i - 1]
                  ? `${(rowData.monthDataList[i - 1][v] * 100).toFixed(3)}%`
                  : '0.0%';
              } else {
                val = rowData.monthDataList[i - 1] ? rowData.monthDataList[i - 1][v] / 10000 : 0.0;
              }
              return val;
            },
            cellRenderer: data => {
              let val = '';
              if (isPercentage) {
                val = data.cellData;
              } else {
                val = <NumberView {...data} precision={4} />;
              }
              return val;
            },
          });
        });
      }
    }
  }
  return fixedColumns;
};

export const getTitleTree = (currentYear, currentMonths, currentVersion) => {
  // 获取版本归属月份---begin
  let getVersionAffiliationMonth = dayjs().format('YYYY-MM');
  // 如果是预算版本类型 取 来源版本的归属月份
  if (currentVersion?.versionType === 'budget') {
    getVersionAffiliationMonth = dayjs(currentVersion?.sourceAffiliationMonth).format('YYYY-MM');
  } else {
    getVersionAffiliationMonth = dayjs(currentVersion?.affiliationMonth).format('YYYY-MM');
  }
  // 获取版本归属月份---end
  const titleTree = [
    {
      name: '分期/组团/产品类型',
      key: 'id',
      colspan: 1,
      rowspan: 5,
      frozen: 'left',
    },
    {
      name: '结转日期',
      key: 'carryOverTimeStr',
      colspan: 1,
      rowspan: 5,
    },
    {
      name: '签约与回款',
      key: 'allSignReturnMoney',
      rowspan: 2,
      children: [],
    },
    {
      name: '',
      isTabs: true,
      key: 'yearTotalCount',
      children: [],
    },
  ];
  // 签约与回款
  titleTree[2].children = [
    {
      name: (
        <TableCell>
          <div>总货值</div>
          <div>(A)</div>
        </TableCell>
      ),
      key: 'allGoodsValue',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>累计已售</div>
          <div>(B=C+D)</div>
        </TableCell>
      ),
      key: 'cumulativeSold',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>累计已回款</div>
          <div>(C)</div>
        </TableCell>
      ),
      key: 'cumulativePaymentReceived',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>已签未回</div>
          <div>(D)</div>
        </TableCell>
      ),
      key: 'SignedNotBack',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>未签未回</div>
          <div>(A-B)</div>
        </TableCell>
      ),
      key: 'notSignedNotBack',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
    {
      name: (
        <TableCell>
          <div>累计签约回款率</div>
          <div>(C/B)</div>
        </TableCell>
      ),
      key: 'accumulativeContractPaymentRateWithoutSigning',
      rowspan: 2,
      marginTop: 1,
      colspan: 1,
    },
  ];
  // table header点击的年份
  const columns = [
    {
      name: `${currentYear}年度`,
      key: `${currentYear}Year`,
      hidden: !_.includes(currentMonths, '14'),
      children: [
        {
          name: '年初应收账款',
          key: `${currentYear}-yearEarlyReceivable`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: '年度签约',
          key: `${currentYear}-yearSign`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: '年度实际数',
          key: `${currentYear}-annualActual`,
          colspan: 2,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualActual-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualActual-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
        {
          name: '年度测算数',
          key: `${currentYear}-annualCalculate`,
          colspan: 2,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualCalculate-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualCalculate-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
        {
          name: '年度调整数',
          key: `${currentYear}-annualAdjust`,
          colspan: 2,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualAdjust-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualAdjust-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
        {
          name: (
            <TableCell>
              <div>年初已签未回</div>
              <div>回款数</div>
            </TableCell>
          ),
          key: `${currentYear}-yearSignNotReturn`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: (
            <TableCell>
              <div>年初应退</div>
              <div>回款数</div>
            </TableCell>
          ),
          key: `${currentYear}-yearEarlyRefund`,
          colspan: 1,
          rowspan: 2,
        },
        {
          name: `${currentYear}年度回款合计`,
          key: `${currentYear}-annualTotal`,
          colspan: 4,
          rowspan: 1,
          children: [
            {
              name: '增量回款',
              key: `${currentYear}-annualTotal-IncrementalReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '存量回款',
              key: `${currentYear}-annualTotal-StoreReturn`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '回款合计',
              key: `${currentYear}-annualTotal-ReturnTotal`,
              colspan: 1,
              rowspan: 1,
            },
            {
              name: '年末应收账款',
              key: `${currentYear}-annualTotal-YearEndReceivable`,
              colspan: 1,
              rowspan: 1,
            },
          ],
        },
      ],
    },
  ];

  for (let i = 1; i <= 12; i += 1) {
    // 是否是当前时间之前
    const isCurrentTimeBefore = dayjs(`${currentYear}-${i}`).isBefore(getVersionAffiliationMonth);
    // 是否是当前时间
    const isCurrentTime = dayjs(`${currentYear}-${i}`).isSame(getVersionAffiliationMonth);
    // 当前月
    if (isCurrentTime) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '期初应收账款',
            key: `${i}-field_6-1`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期签约',
            key: `${i}-monthSign-1`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期实际数',
            key: `${i}-monthlyActual-1`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyActualIncrementalReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyActualStoreReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '本期测算数',
            key: `${i}-monthlyCalculate-1`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyCalculateIncrementalReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyCalculateStoreReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '本期调整数',
            key: `${i}-monthlyAdjust-1`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyAdjustIncrementalReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyAdjustStoreReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: (
              <TableCell>
                <div>本期已签未回</div>
                <div>回款数</div>
              </TableCell>
            ),
            key: `${i}-monthSignNotReturn-1`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: (
              <TableCell>
                <div>本期期初应退</div>
                <div>回款数</div>
              </TableCell>
            ),
            key: `${i}-refundable-1`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期回款合计',
            key: `${i}-monthlyTotal-1`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyTotalIncrementalReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyTotalStoreReturn-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '回款合计',
                key: `${i}-monthlyTotalReturnTotal-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '期末应收账款',
                key: `${i}-monthlyTotalMonthEndReceivable-1`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '回款率',
            key: `${i}-ReturnRate-1`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '累计签约回款率',
                key: `${currentYear}${i}-signReturnRate-1`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '年度综合回款率',
                key: `${currentYear}${i}-annualOverallReturnRate-1`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
        ],
      });
    }
    // 实际月
    if (!isCurrentTime && isCurrentTimeBefore) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '期初应收账款',
            key: `${i}-field_6-2`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期签约',
            key: `${i}-monthSign-2`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期回款合计（实际数）',
            key: `${i}-monthlyTotal-2`,
            colspan: 3,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyTotalIncrementalReturn-2`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyTotalStoreReturn-2`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '回款合计',
                key: `${i}-monthlyTotalReturnTotal-2`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '回款率',
            key: `${i}-ReturnRate-2`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '累计签约回款率',
                key: `${i}-signReturnRate-2`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '年度综合回款率',
                key: `${i}-annualOverallReturnRate-2`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
        ],
      });
    }
    // 计划月
    if (!isCurrentTime && !isCurrentTimeBefore) {
      columns.push({
        name: `${currentYear}-${i < 10 ? '0' : ''}${i}`,
        key: `${currentYear}${i}`,
        hidden: !_.includes(currentMonths, i.toString()),
        children: [
          {
            name: '期初应收账款',
            key: `${i}-field_6-3`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期签约',
            key: `${i}-monthSign-3`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期测算数',
            key: `${i}-monthlyCalculate-3`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyCalculateIncrementalReturn-3`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyCalculateStoreReturn-3`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '本期调整数',
            key: `${i}-monthlyAdjust-3`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyAdjustIncrementalReturn-3`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyAdjustStoreReturn-3`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: (
              <TableCell>
                <div>本期已签未回</div>
                <div>回款数</div>
              </TableCell>
            ),
            key: `${i}-monthSignNotReturn-3`,
            colspan: 1,
            rowspan: 2,
          },
          {
            name: '本期回款合计',
            key: `${i}-monthlyTotal-3`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '增量回款',
                key: `${i}-monthlyTotalIncrementalReturn-3`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '存量回款',
                key: `${i}-monthlyTotalStoreReturn-3`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '回款合计',
                key: `${i}-monthlyTotalReturnTotal-3`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '期末应收账款',
                key: `${i}-monthlyTotalMonthEndReceivable-3`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
          {
            name: '回款率',
            key: `${i}-ReturnRate-3`,
            colspan: 2,
            rowspan: 1,
            children: [
              {
                name: '累计签约回款率',
                key: `${i}-signReturnRate-3`,
                colspan: 1,
                rowspan: 1,
              },
              {
                name: '年度综合回款率',
                key: `${i}-annualOverallReturnRate-3`,
                colspan: 1,
                rowspan: 1,
              },
            ],
          },
        ],
      });
    }
  }
  titleTree[3].children = columns;
  return titleTree;
};

export const headerRenderer = (titleTree, currentYear, overAllYears, dispatch) => {
  const headerRender = utils.getHeaderRenderer(titleTree, 4, () => (
    <YearsRender currentYear={currentYear} overAllYears={overAllYears} dispatch={dispatch} />
  ));
  return headerRender;
};

// 回款计划编辑
// 改变所有string数值为Number类型
export const allStringModifyNumber = (list, fields) => {
  const cloneList = _.cloneDeep(list);
  _.forEach(cloneList, monthData => {
    const monthDataX = monthData;
    monthDataX.totalValue = _.toNumber(monthDataX.totalValue);
    _.forEach(monthData.detailList, val => {
      const x = val;
      for (let i = 0; i < fields.length; i += 1) {
        x[fields[i]] = val[fields[i]] ? _.toNumber(val[fields[i]]) : 0;
      }
      // x.signReturnRate = val.signReturnRate ? _.toNumber(val.signReturnRate) : 0;
      // x.annualOverallReturnRate = val.annualOverallReturnRate
      //   ? _.toNumber(val.annualOverallReturnRate)
      //   : 0;
    });
  });
  return cloneList;
};

// 根据回款计划数据生成年月
export const recalculateSupplyDates = ({ earliestYearMonth, latestYearMonth }) => {
  const supplyDates = [];
  const minYear = dayjs(earliestYearMonth).year(); // 最小年
  const maxYear = dayjs(latestYearMonth).year(); // 最大年
  // 根据最小年和最大年生成年份list
  for (let year = minYear; year <= maxYear; year += 1) {
    const monthList = [];
    for (let month = 1; month < 13; month += 1) {
      monthList.push({
        value: month,
        disabled: dayjs(`${year}-${month}`).isBefore(earliestYearMonth),
        error: false,
        isEdit: false,
      });
    }
    supplyDates.push({
      title: year,
      closable: false,
      error: false,
      isEdit: false,
      monthList,
    });
  }
  return supplyDates;
};

// 设置年月编辑提示
export const setSupplyDatesEdit = (list, data) => {
  const cloneList = _.cloneDeep(list);
  _.forEach(cloneList, yearItem => {
    const y = yearItem;
    y.isEdit = false;
    _.forEach(yearItem.monthList, monthItem => {
      const m = monthItem;
      m.isEdit = false;
      _.forEach(data, ({ detailList }) => {
        _.forEach(
          detailList,
          ({ incrementReturnAmountAdjust, storeReturnAmountAdjust, returnTime }) => {
            if (
              dayjs(returnTime).year() === yearItem.title &&
              dayjs(returnTime).month() + 1 === monthItem.value
            ) {
              if (incrementReturnAmountAdjust !== 0 || storeReturnAmountAdjust !== 0) {
                y.isEdit = true;
                m.isEdit = true;
              }
            }
          },
        );
      });
    });
  });
  return cloneList;
};

// 循环计算之后所有的月
export const setLoopMonth = (list, editYearMonth) => {
  let stopLoop = false;
  let prevReturnAmountTotal = 0; // 累计上月回款合计
  let prevSignAmountTotal = 0; // 累计上月签约合计
  let prevYearReturnAmountTotal = 0; // 一年累计上月回款合计
  let prevYearSignAmountTotal = 0; // 一年累计上月签约合计
  let januaryEarlyReceivableAmount = 0; // 当前年一月 期初应收
  let lastMonthFinalReceivable = 0; // 上月的期末应收
  // 上个月
  const previousMonth = dayjs(editYearMonth)
    .subtract(1, 'months')
    .format('YYYY-MM');
  // 下个月
  const nextMonth = dayjs(editYearMonth)
    .add(1, 'months')
    .format('YYYY-MM');
  // 计算
  _.forEach(list, monthItem => {
    const time = dayjs(monthItem.returnTime).format('YYYY-MM');
    // 上个月的数据
    if (previousMonth === time) {
      lastMonthFinalReceivable = monthItem.finalReceivable;
      prevReturnAmountTotal = monthItem.returnAmountTotal;
      prevSignAmountTotal = monthItem.signAmountTotal;
    }
    // 当年数据
    if (dayjs(editYearMonth).year() === dayjs(monthItem.returnTime).year()) {
      if (previousMonth === time) {
        prevYearReturnAmountTotal = monthItem.yearReturnAmountTotal;
        prevYearSignAmountTotal = monthItem.yearSignAmountTotal;
      }
      const x = monthItem;
      // 一月数据
      if (dayjs(`${dayjs(editYearMonth).year()}-01`).isSame(time)) {
        januaryEarlyReceivableAmount = monthItem.earlyReceivableAmount;
      }
      // 当月的数据
      if (dayjs(editYearMonth).month() === dayjs(monthItem.returnTime).month()) {
        // console.log(prevSignAmountTotal, prevReturnAmountTotal, `${monthItem.returnTime}`)
        stopLoop = true;
        // 本月累计签约合计 = 上月累计签约合计 + 当月签约金额
        x.signAmountTotal = prevSignAmountTotal + monthItem.signAmount;
        // 本月累计回款合计 = 上月累计回款合计 + 当月回款合计金额
        x.returnAmountTotal = prevReturnAmountTotal + monthItem.totalReturnAmount;
        // 年累计签约合计 = 上月年累计签约合计 + 当月签约金额
        x.yearSignAmountTotal = prevYearSignAmountTotal + monthItem.signAmount;
        // 年累计回款合计 = 上月年累计回款合计 + 当月回款合计金额
        x.yearReturnAmountTotal = prevYearReturnAmountTotal + monthItem.totalReturnAmount;
        // 本月期初应收 = 上月期末应收
        x.earlyReceivableAmount = lastMonthFinalReceivable;
        // 本月已签未回 = 上月期末应收 + 当月签约金额 - 当月回款合计
        x.signedUnrecovered = lastMonthFinalReceivable + x.signAmount - x.totalReturnAmount;
        // 本月期末应收 = 本月已签未回
        x.finalReceivable = x.signedUnrecovered;
        // 累计签约回款率 = 本月累计回款合计 / 本月累计签约合计
        if (x.signAmountTotal === 0) {
          x.signReturnRate = 0;
        } else {
          x.signReturnRate = x.returnAmountTotal / x.signAmountTotal;
        }
        // 年度综合回款率 = 年累计回款合计 / (年一月的期初应收  + 年累计签约合计)
        if (x.yearSignAmountTotal + januaryEarlyReceivableAmount === 0) {
          x.annualOverallReturnRate = 0;
        } else {
          x.annualOverallReturnRate =
            x.yearReturnAmountTotal / (x.yearSignAmountTotal + januaryEarlyReceivableAmount);
        }
      }
    }
  });
  // 到最晚一个月
  if (stopLoop) {
    setLoopMonth(list, nextMonth);
  }
};

// 计算本期回款
export const setRowMonth = list => {
  const monthData = list;
  // 本期回款-增量回款 = 测算数增量回款 + 调整数增量回款
  monthData.incrementReturnAmount =
    monthData.incrementReturnAmountCalculate + monthData.incrementReturnAmountAdjust;
  // // 本期回款-存量回款 = 测算数存量回款 + 调整数存量回款 + 本期应收 + 上月应收未收 - 期初应退)
  // 本期回款-存量回款 = 测算数存量回款 + 调整数存量回款 + 本期应收 + 上月应收未收)
  monthData.storeReturnAmount =
    monthData.storeReturnAmountCalculate +
    monthData.storeReturnAmountAdjust +
    monthData.lastMonthNotReceivableAmount +
    monthData.receivableAmount;
  // monthData.refundable;
  // 本期回款-回款合计 = 本期回款增量回款 + 本期回款存量回款
  monthData.totalReturnAmount = monthData.incrementReturnAmount + monthData.storeReturnAmount;
  return monthData;
};

// 循环计算之后所有的数据
const loopCountAllData = (YearMonthList, currentYearMonth) => {
  let isLoop = false;
  // 上个月
  const lastMonth = dayjs(currentYearMonth)
    .subtract(1, 'months')
    .format('YYYY-MM');
  // 下个月
  const nextMonth = dayjs(currentYearMonth)
    .add(1, 'months')
    .format('YYYY-MM');
  // 获取上月数据
  const [getLastMothData] = _.filter(YearMonthList, x => {
    const time = dayjs(x.returnTime).format('YYYY-MM');
    if (lastMonth === time) return true;
    return false;
  });
  // 获取当前年上月数据
  const [getYearLastMonthData] = _.filter(YearMonthList, x => {
    const year = dayjs(x.returnTime).format('YYYY');
    const time = dayjs(x.returnTime).format('YYYY-MM');
    if (lastMonth === time) {
      if (year === dayjs(currentYearMonth).format('YYYY')) {
        return true;
      }
    }
    return false;
  });
  // 获取当前年一月数据
  const [getYearOneMonthData] = _.filter(YearMonthList, x => {
    const time = dayjs(x.returnTime).format('YYYY-MM');
    if (dayjs(`${dayjs(currentYearMonth).year()}-01`).isSame(time)) return true;
    return false;
  });
  // 复制累计上月数据
  const prevReturnAmountTotal = getLastMothData?.returnAmountTotal || 0; // 累计上月回款合计
  const prevSignAmountTotal = getLastMothData?.signAmountTotal || 0; // 累计上月签约合计
  const lastMonthFinalReceivable = getLastMothData?.finalReceivable || 0; // 上月的期末应收
  // 复制累计年数据
  const prevYearReturnAmountTotal = getYearLastMonthData?.yearReturnAmountTotal || 0; // 一年累计上月回款合计
  const prevYearSignAmountTotal = getYearLastMonthData?.yearSignAmountTotal || 0; // 一年累计上月签约合计
  // 复制年一月数据
  const januaryEarlyReceivableAmount = getYearOneMonthData?.earlyReceivableAmount || 0; // 当前年一月 期初应收
  // 传入月份的数据计算
  _.forEach(YearMonthList, monthData => {
    if (dayjs(currentYearMonth).isSame(monthData.returnTime, 'month')) {
      isLoop = true;
      const x = monthData;
      // 本期回款-增量回款 = 测算数增量回款 + 调整数增量回款
      x.incrementReturnAmount = x.incrementReturnAmountCalculate + x.incrementReturnAmountAdjust;
      // 本期回款-存量回款 = 测算数存量回款 + 调整数存量回款 + 本期应收 + 上月应收未收)
      x.storeReturnAmount =
        x.storeReturnAmountCalculate +
        x.storeReturnAmountAdjust +
        x.lastMonthNotReceivableAmount +
        x.receivableAmount;
      // 本期回款-回款合计 = 本期回款增量回款 + 本期回款存量回款
      x.totalReturnAmount = x.incrementReturnAmount + x.storeReturnAmount;
      // 本月累计签约合计 = 上月累计签约合计 + 当月签约金额
      x.signAmountTotal = prevSignAmountTotal + x.signAmount;
      // 本月累计回款合计 = 上月累计回款合计 + 当月回款合计金额
      x.returnAmountTotal = prevReturnAmountTotal + x.totalReturnAmount;
      // 年累计签约合计 = 上月年累计签约合计 + 当月签约金额
      x.yearSignAmountTotal = prevYearSignAmountTotal + x.signAmount;
      // 年累计回款合计 = 上月年累计回款合计 + 当月回款合计金额
      x.yearReturnAmountTotal = prevYearReturnAmountTotal + x.totalReturnAmount;
      // 本月期初应收 = 上月期末应收
      x.earlyReceivableAmount = lastMonthFinalReceivable;
      // 本月已签未回 = 上月期末应收 + 当月签约金额 - 当月回款合计
      x.signedUnrecovered = lastMonthFinalReceivable + x.signAmount - x.totalReturnAmount;
      // 本月期末应收 = 本月已签未回
      x.finalReceivable = x.signedUnrecovered;

      // 累计率
      // 累计签约回款率 = 本月累计回款合计 / 本月累计签约合计
      if (x.signAmountTotal) {
        x.signReturnRate = x.returnAmountTotal / x.signAmountTotal;
      }

      // 年度综合回款率 = 年累计回款合计 / (年一月的期初应收  + 年累计签约合计)
      if (x.yearSignAmountTotal + januaryEarlyReceivableAmount) {
        x.annualOverallReturnRate =
          x.yearReturnAmountTotal / (x.yearSignAmountTotal + januaryEarlyReceivableAmount);
      }
    }
  });
  // 到最晚一个月
  if (isLoop) {
    setLoopMonth(YearMonthList, nextMonth);
  }
};

// 重新计算归属月之后的所有业态
export const regenerateData = (list, yearMonth) => {
  const cloneList = _.cloneDeep(list);
  // 循环每条业态
  _.forEach(cloneList, ({ detailList }) => {
    loopCountAllData(detailList, yearMonth);
    // TODO 循环每条年月
    // _.forEach(detailList, monthData => {
    //   if (dayjs(yearMonth).isSame(monthData.returnTime, 'month')) {
    //     setRowMonth(monthData);
    //   }
    // });
    // setLoopMonth(detailList, yearMonth);
  });
  return cloneList;
};

// 重新计算当前编辑业态之后月份的数据
export const modifyRowData = ({ list, key, val, yearMonth, id }) => {
  const cloneList = _.cloneDeep(list);
  // let lastMonthReturnAmountTotal = 0; // 上月回款累计金额
  // let lastMonthSignAmountTotal = 0; // 上月累计签约金额
  // 上个月
  // const previousMonth = dayjs(yearMonth)
  //   .subtract(1, 'months')
  //   .format('YYYY-MM');
  _.forEach(cloneList, ({ detailList, combinationProductCode, totalValue }) => {
    if (id === combinationProductCode) {
      _.forEach(detailList, monthData => {
        // console.log()
        // const time = dayjs(monthData.returnTime).format('YYYY-MM');
        // // 取上个月
        // if (previousMonth === time) {
        //   lastMonthReturnAmountTotal = monthData.returnAmountTotal;
        //   lastMonthSignAmountTotal = monthData.signAmountTotal;
        // }
        if (dayjs(yearMonth).isSame(monthData.returnTime, 'month')) {
          const x = monthData;
          // ? 调整数增量回款上限 = 总货值 - 上月回款累计金额 - 测算数增量回款 -本月回款存量回款
          // if (key === 'incrementReturnAmountAdjust') {
          //   const upperLimit =
          //     totalValue -
          //     lastMonthReturnAmountTotal -
          //     monthData.incrementReturnAmountCalculate -
          //     monthData.storeReturnAmount;
          //   if (val > upperLimit) {
          //     x[key] = upperLimit;
          //   } else {
          //     x[key] = val;
          //   }
          // }
          // ? 调整数存量回款上限 = 上月累计签约金额 - 上月回款累计金额 -当前月存量回款测算数 -当前月供款计划存量回款
          // if (key === 'storeReturnAmountAdjust') {
          //   const upperLimit =
          //     lastMonthSignAmountTotal -
          //     lastMonthReturnAmountTotal -
          //     monthData.storeReturnAmountCalculate -
          //     monthData.storeReturnAmount;
          //   if (val > upperLimit) {
          //     x[key] = upperLimit;
          //   } else {
          //     x[key] = val;
          //   }
          // }
          x[key] = val;
          // setRowMonth(monthData);
        }
      });
      loopCountAllData(detailList, yearMonth);
    }
  });
  return cloneList;
};

// 组成表格需要的格式
export const buildTableData = (list, yearMonth, fields) => {
  const cloneList = _.cloneDeep(list);
  const treeData = [];
  _.forEach(cloneList, ({ combinationProductCode, detailList }) => {
    const [monthData] = _.filter(detailList, ({ returnTime }) =>
      dayjs(yearMonth).isSame(returnTime, 'month'),
    );
    const x = monthData;
    for (let i = 0; i < fields.length; i += 1) {
      if (fields[i] === 'signReturnRate' || fields[i] === 'annualOverallReturnRate') {
        x[fields[i]] = monthData[fields[i]] * 100;
      } else {
        x[fields[i]] = monthData[fields[i]] / 10000;
      }
    }
    treeData.push({
      errorIncrement: 'success',
      errorStock: 'success',
      combinationProductCode,
      ...x,
    });
  });
  return treeData;
};

// 计算全周期金额
export const countAllPeriodVal = (list, last) => {
  let returnAmountTotal = 0;
  let finalReceivableTotal = 0;
  let isSave = false;
  const lastList = [];
  _.forEach(list, productItem => {
    // 本期全周期回款金额合计
    _.forEach(productItem.detailList, monthData => {
      // 取最后一年最后一个月的数据
      if (
        dayjs(
          dayjs(last)
            .endOf('year')
            .format('YYYY-MM'),
        ).isSame(monthData.returnTime, 'month')
      ) {
        lastList.push(monthData);
        // 期末应收合计
        finalReceivableTotal += monthData.finalReceivable;
        // 累计回款合计
        returnAmountTotal += monthData.returnAmountTotal;
        // 校验是否可以保存 每个业态上下容差100元
        if (Math.abs(monthData.finalReceivable) > 100) isSave = true;
      }
    });
  });
  return {
    returnAmountTotal: _.round(returnAmountTotal, 4),
    finalReceivableTotal: _.round(finalReceivableTotal, 4),
    isSave,
    lastList,
  };
};

// 删除无效的数据
export const verificationSaveParams = list => {
  const cloneList = _.cloneDeep(list);
  // 是否可以删除
  const isDelete = _.last(list).isAllowedDelete === 1;
  // 期末应收是否为空
  const isFinalReceivableEmpty = _.last(list).finalReceivable === 0;
  // 回款合计是否为空
  const isTotalReturnAmountEmpty = _.last(list).totalReturnAmount === 0;
  // 签约金额是否为空
  const isSignAmountEmpty = _.last(list).signAmount === 0;
  if (isDelete && isFinalReceivableEmpty && isTotalReturnAmountEmpty && isSignAmountEmpty) {
    return verificationSaveParams(_.slice(cloneList, 0, cloneList.length - 1));
  }
  return cloneList;
};

/**
 * 全盘回款概览
 * 设置表格头部
 * */
export const changeSetColumns = (year, month) => {
  const columns = {
    projectColumns: [
      {
        title: '项目/业态',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: `${year}年${month}月月度回款`,
        dataIndex: 'monthlyReturnedMoney',
        key: 'monthlyReturnedMoney',
        width: 130,
        align: 'right',
      },
      {
        title: `${year}年度回款`,
        dataIndex: 'annualReturnedMoney',
        key: 'annualReturnedMoney',
        width: 100,
        align: 'right',
      },
      {
        title: `${_.toNumber(year) + 1}年度回款`,
        dataIndex: 'nextYearReturnedMoney',
        key: 'nextYearReturnedMoney',
        width: 100,
        align: 'right',
      },
      {
        title: '项目剩余应收账款',
        dataIndex: 'residualReceivables',
        key: 'residualReceivables',
        width: 110,
        align: 'right',
      },
    ],
    stagesColumns: [
      {
        title: '分期/业态',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: `${year}年${month}月月度回款`,
        dataIndex: 'monthlyReturnedMoney',
        key: 'monthlyReturnedMoney',
        width: 130,
        align: 'right',
      },
      {
        title: `${year}年度回款`,
        dataIndex: 'annualReturnedMoney',
        key: 'annualReturnedMoney',
        width: 100,
        align: 'right',
      },
      {
        title: `${_.toNumber(year) + 1}年度回款`,
        dataIndex: 'nextYearReturnedMoney',
        key: 'nextYearReturnedMoney',
        width: 100,
        align: 'right',
      },
      {
        title: '分期剩余应收账款',
        dataIndex: 'residualReceivables',
        key: 'residualReceivables',
        width: 110,
        align: 'right',
      },
    ],
  };
  return columns;
};

/**
 * 全盘回款概览
 * 设置表格数据
 * */
export const changeSetData = (
  currentList, // 当前月所有的业态
  requestList, // 初始化全盘数据
  currentId, // 当前id
  year,
  month,
  lastTime, // 最后时间
  version,
) => {
  const CLONE_LIST = _.cloneDeep(requestList);
  // 容器
  const DATA_SOURCE = {
    projectData: [],
    stagesData: [],
  };
  // 改为数字类型
  _.forEach(CLONE_LIST, item => {
    const X_ITEM = item;
    X_ITEM.monthlyReturnedMoney *= 1;
    X_ITEM.annualReturnedMoney *= 1;
    X_ITEM.nextYearReturnedMoney *= 1;
    X_ITEM.residualReceivables *= 1;
  });
  // 如果当前编辑取编辑的值 否则取原数据
  if (currentId) {
    _.forEach(currentList, ({ detailList, combinationProductCode }) => {
      _.forEach(detailList, monthData => {
        // 替换当前业态
        _.forEach(CLONE_LIST, rowData => {
          // 组合业态code一样的
          const PRODUCT_CODE_IS_SAME = rowData.combinationProductCode === combinationProductCode;
          // 版本id一样的
          const VERSION_ID_IS_SAME = rowData.versionId === monthData.versionId;
          // 组团id一样的
          const GROUP_ID_IS_SAME = rowData.groupId === monthData.groupId;
          if (PRODUCT_CODE_IS_SAME && VERSION_ID_IS_SAME && GROUP_ID_IS_SAME) {
            const x = rowData;
            if (dayjs(`${year}-${month}`).isSame(monthData.returnTime, 'month')) {
              x.monthlyReturnedMoney = monthData.totalReturnAmount;
            }
            if (dayjs(`${year}-12`).isSame(monthData.returnTime, 'month')) {
              x.annualReturnedMoney = monthData.yearReturnAmountTotal;
            }
            if (dayjs(`${year * 1 + 1}-12`).isSame(monthData.returnTime, 'month')) {
              x.nextYearReturnedMoney = monthData.yearReturnAmountTotal;
            }
            if (dayjs(lastTime).isSame(monthData.returnTime, 'month')) {
              x.residualReceivables = monthData.finalReceivable;
            }
          }
        });
      });
    });
  }

  function mergeArr(arr) {
    const cloneArr = _.cloneDeep(arr);
    const newArr = [];
    cloneArr.forEach(item => {
      const dataItem = item;
      if (newArr.length > 0) {
        const filterValue = newArr.filter(
          v => v.combinationProductCode === dataItem.combinationProductCode,
        );
        if (filterValue.length > 0) {
          newArr.forEach(n => {
            const X_N = n;
            if (n.combinationProductCode === filterValue[0].combinationProductCode) {
              X_N.monthlyReturnedMoney =
                filterValue[0].monthlyReturnedMoney + dataItem.monthlyReturnedMoney;
              X_N.annualReturnedMoney =
                filterValue[0].annualReturnedMoney + dataItem.annualReturnedMoney;
              X_N.nextYearReturnedMoney =
                filterValue[0].nextYearReturnedMoney + dataItem.nextYearReturnedMoney;
              X_N.residualReceivables =
                filterValue[0].residualReceivables + dataItem.residualReceivables;
            }
          });
        } else {
          newArr.push(dataItem);
        }
      } else {
        newArr.push(dataItem);
      }
    });
    return newArr;
  }

  // 项目
  // 合并相同的业态
  _.forEach(mergeArr(CLONE_LIST), rowData => {
    DATA_SOURCE.projectData.push({
      name: `${rowData.productName}-${rowData.proTypeName}-${rowData.freeTypeName}-${rowData.businessTypeName}`,
      monthlyReturnedMoney: _.round(rowData.monthlyReturnedMoney / 10000, 4),
      annualReturnedMoney: _.round(rowData.annualReturnedMoney / 10000, 4),
      nextYearReturnedMoney: _.round(rowData.nextYearReturnedMoney / 10000, 4),
      residualReceivables: _.round(rowData.residualReceivables / 10000, 4),
      projectName: rowData.projectName,
    });
  });
  // 分期
  const currentStages = _.filter(CLONE_LIST, x => x.versionId === version);
  _.forEach(mergeArr(currentStages), rowData => {
    DATA_SOURCE.stagesData.push({
      name: `${rowData.productName}-${rowData.proTypeName}-${rowData.freeTypeName}-${rowData.businessTypeName}`,
      monthlyReturnedMoney: _.round(rowData.monthlyReturnedMoney / 10000, 4),
      annualReturnedMoney: _.round(rowData.annualReturnedMoney / 10000, 4),
      nextYearReturnedMoney: _.round(rowData.nextYearReturnedMoney / 10000, 4),
      residualReceivables: _.round(rowData.residualReceivables / 10000, 4),
      stageName: rowData.stageName,
    });
  });
  // 新增一行项目合计，分期合计
  function countTotal(list, name) {
    let totalObject = {};
    totalObject = _.reduce(
      list,
      (sum, n) => ({
        name,
        monthlyReturnedMoney: _.round(sum.monthlyReturnedMoney + n.monthlyReturnedMoney, 4),
        annualReturnedMoney: _.round(sum.annualReturnedMoney + n.annualReturnedMoney, 4),
        nextYearReturnedMoney: _.round(sum.nextYearReturnedMoney + n.nextYearReturnedMoney, 4),
        residualReceivables: _.round(sum.residualReceivables + n.residualReceivables, 4),
      }),
      {
        name,
        monthlyReturnedMoney: 0,
        annualReturnedMoney: 0,
        nextYearReturnedMoney: 0,
        residualReceivables: 0,
      },
    );
    return totalObject;
  }
  // 项目合计
  const PROJECT_TOTAL = countTotal(
    DATA_SOURCE.projectData,
    _.head(DATA_SOURCE.projectData).projectName,
  );
  // 分期合计
  const STAGES_TOTAL = countTotal(DATA_SOURCE.stagesData, _.head(DATA_SOURCE.stagesData).stageName);
  DATA_SOURCE.projectData.unshift(PROJECT_TOTAL);
  DATA_SOURCE.stagesData.unshift(STAGES_TOTAL);
  // 转换成表格需要的格式
  return DATA_SOURCE;
};
